package com.beamfield.controller.manage.sys;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.beamfield.model.Supplies;
import com.beamfield.modelVo.TreeVo;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.beamfield.common.ApiResult;
import com.beamfield.common.PageResult;
import com.beamfield.controller.common.BaseController;
import com.beamfield.dictionary.code;
import com.beamfield.enums.HttpResultEnum;
import com.beamfield.modelVo.ProductVo;
import com.beamfield.modelVo.SystemDictionaryDataVo;
import com.beamfield.service.manage.sys.DictonaryService;
import com.beamfield.service.manage.sys.SuppliesService;

/**
 * 材料初始化
 *
 * @author mintonzhang@163.com
 * @date 2018年6月8日
 */
@RestController
@RequestMapping("/cms")
public class SuppliesController extends BaseController {

	@Autowired
	SuppliesService suppliesService;

	@Resource
	DictonaryService dictonaryService;

	@Value("${session.user}")
	private String user;

	@Value("${session.beam}")
	private String beam;

	@RequestMapping("/sys/supplies_list")
	public ModelAndView supplies() {
		return new ModelAndView();
	}

	@RequestMapping("/sys/productTitle")
	public ModelAndView productTitle() {
		return new ModelAndView();
	}

	@RequestMapping("/sys/materialClassification")
	public ModelAndView materialClassification() {
		return new ModelAndView();
	}

    @RequestMapping("/supplies/materialApproach/bigMaterialApproach")
    public ModelAndView bigMaterialApproach() {
        return new ModelAndView();
    }

	@RequestMapping("/supplies/materialApproach/storageDetails")
	public ModelAndView storageDetails() {
		return new ModelAndView();
	}

	@RequestMapping("/sys/reset")
	public ApiResult reset(HttpServletRequest req) {
		try {
			MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
			MultipartFile file = mRequest.getFile("file");
			InputStream in = file.getInputStream();
			byte[] data = IOUtils.toByteArray(in);
			Workbook wb = null;
			try {
				wb = new HSSFWorkbook(new ByteArrayInputStream(data));
			} catch (Exception e) {
				wb = new XSSFWorkbook(new ByteArrayInputStream(data));
			}
			int status = suppliesService.reset(wb, getUserId(req), getBeamId(req));
			if (status == 0) {
				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
			}
		} catch (Exception e) {
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), HttpResultEnum.EXCEPTION.getMessage());
		}
		return new ApiResult();
	}

	@RequestMapping("/sys/getProduct")
	public PageResult getProduct(HttpServletRequest req) {
		List<ProductVo> selectAll = suppliesService.getProduct(getBeamId(req));
		return new PageResult(selectAll.size(), 1, selectAll);

	}
	@RequestMapping("/sys/listData")
	public PageResult listData(HttpServletRequest req, String project_id,String title) {
		List<ProductVo> selectAll = suppliesService.selectAll(getBeamId(req), project_id,title);
		return new PageResult(selectAll.size(), 1, selectAll);

	}

	@RequestMapping("/sys/getDetailed")
	public PageResult getDetailed(HttpServletRequest req, String productid, Integer offset, Integer limit) {
		return suppliesService.getProductDetailed(getBeamId(req), productid, offset, limit);
	}

	/**
	 * 物资分类集合
	 * @return
	 */
	@RequestMapping("/sys/getSuppliesType")
	@ResponseBody
	public ApiResult getSuppliesType(HttpSession session) {
		 long beam_id = (long) session.getAttribute(beam);
		 List<SystemDictionaryDataVo> supplies = dictonaryService.getDicByCode(code.supplies,beam_id);
		 return new ApiResult("1","物资分类",supplies);
	}


	/**
	 * 材料分类
	 *
	 * @param session
	 * @param supplies_ids
	 * @param code
	 * @return
	 */
	@RequestMapping("/sys/updateSuppliesType")
	@ResponseBody
	public ApiResult updateSuppliesType(HttpSession session, String supplies_ids, String code) {
		Long user_id = (Long) session.getAttribute(user);
		ApiResult apiResult=suppliesService.materialClassification(code,supplies_ids,user_id);
		return apiResult;
	}

	/**
	 * 未分类的材料分页数据
	 *
	 * @param session
	 * @param supplies_material_name
	 * @param supplies_name
	 * @param supplies_material_standard
	 * @param offset
	 * @param limit
	 * @return
	 */
	@RequestMapping("/sys/selectSuppliesPage")
	@ResponseBody
	public PageResult selectSuppliesPage(HttpSession session, String supplies_material_name, String supplies_name, String supplies_material_standard, Integer offset, Integer limit){
		Long beam_id = (Long) session.getAttribute(beam);
		PageResult pageResult=suppliesService.selectSuppliesPage(beam_id,supplies_material_name,supplies_name,supplies_material_standard,offset,limit);
		return pageResult;
	}

	@RequestMapping("/sys/updateSuppliesTestItem")
	@ResponseBody
	public ApiResult updateSuppliesTestItem(HttpServletRequest request){
		String suppliesIds = request.getParameter("supplies_ids");
		String parameters = request.getParameter("parameters");
		suppliesService.updateSuppliesTestItem(suppliesIds, parameters);
		return new ApiResult();
	}


	/**
	 * 上传材料图片
	 * @param request
	 * @param multipartFile
	 * @return
	 */
	@RequestMapping(value = "/sys/uploadImg",method = RequestMethod.POST)
	@ResponseBody
	public ApiResult uploadImg(HttpServletRequest request, @RequestParam("img") MultipartFile multipartFile){
        String suppliesId = request.getParameter("suppliesId");
        if(StringUtils.isEmpty(suppliesId) || multipartFile == null){
            return new ApiResult(HttpResultEnum.MIS_PARAM.getCode(),HttpResultEnum.MIS_PARAM.getMessage());
        }
        Long userId = super.getUserId(request);
        Supplies supplies = new Supplies();
        supplies.setSupplies_id(suppliesId);
        supplies.setUpdater(userId);
        supplies.setUpdatetime(new Date());
        int result = 0;
        try{
            long imgId = super.saveFile((CommonsMultipartFile) multipartFile);
            supplies.setImg_id(imgId);
            result = suppliesService.update(supplies);
        }catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
		}
		if(result ==  1){
            return new ApiResult(HttpResultEnum.SUCCESS.getCode(),"上传成功");
        }
        return new ApiResult(HttpResultEnum.EXCEPTION.getCode(),HttpResultEnum.EXCEPTION.getMessage());
	}

	/**
	 * 获取梁场下的所有材料名
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/sys/getSuppliesName",method = RequestMethod.GET)
	public ApiResult getSuppliesName(HttpServletRequest request){
        Long beamId = super.getBeamId(request);
        List<String> suppliesName = suppliesService.getSuppliesName(beamId);
        List<TreeVo> treeVoList = new ArrayList<>();
        suppliesName.forEach( name -> treeVoList.add(new TreeVo(name)) );
        return new ApiResult(treeVoList);
    }

    @ResponseBody
	@RequestMapping(value = "/sys/saveSupplies")
    public ApiResult saveSupplies(HttpServletRequest request){
		Long beamId = super.getBeamId(request);
		Long userId = super.getUserId(request);
		String suppliesJson = request.getParameter("suppliesJson");
		if(StringUtils.isBlank(suppliesJson)){
			return new ApiResult(HttpResultEnum.MIS_PARAM);
		}
		try {
			int i = suppliesService.saveSupplies(beamId, userId, suppliesJson);
			if(i == 1){
				return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
			}else if (i == 2){
				return new ApiResult(HttpResultEnum.EXCEPTION.getCode(), "存在相同名称、规格的材料");
			}else{
				return new ApiResult(HttpResultEnum.EXCEPTION);
			}

		}catch (Exception e){
			e.printStackTrace();
			return new ApiResult(HttpResultEnum.EXCEPTION);
		}
	}

	@ResponseBody
	@RequestMapping(value = "/sys/deleteSupplies")
	public ApiResult deleteSupplies(HttpServletRequest request){
		String suppliesId = request.getParameter("suppliesId");
		if(StringUtils.isBlank(suppliesId)){
			return new ApiResult(HttpResultEnum.MIS_PARAM);
		}
		return suppliesService.deleteSupplies(suppliesId);
	}

	@ResponseBody
	@RequestMapping(value = "/sys/getSuppliesForProduct")
	public ApiResult getSuppliesForProduct(HttpServletRequest request){
		String productId = request.getParameter("productId");
		Long beamId = super.getBeamId(request);
		if(StringUtils.isBlank(productId)){
			return new ApiResult(HttpResultEnum.MIS_PARAM);
		}
		return new ApiResult(suppliesService.getSuppliesForProduct(productId, beamId));
	}

	@ResponseBody
	@RequestMapping("/sys/saveProductBasicSupplies")
	public ApiResult saveProductBasicSupplies(HttpServletRequest request){
		String suppliesId = request.getParameter("suppliesId");
		String num = request.getParameter("num");
		String pid = request.getParameter("pid");
		if(StringUtils.isBlank(suppliesId) || StringUtils.isBlank(num) || StringUtils.isBlank(pid)){
			return new ApiResult(HttpResultEnum.MIS_PARAM);
		}
		Long beamId = super.getBeamId(request);
		Long userId = super.getUserId(request);
		int i = suppliesService.saveProductBasicSupplies(beamId, userId, suppliesId, num, pid);
		if(i == 1){
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
		}else {
			return new ApiResult(HttpResultEnum.EXCEPTION);
		}
	}

	@ResponseBody
	@RequestMapping("/sys/updateProductBasicSuppliesNum")
	public ApiResult updateProductBasicSuppliesNum(HttpServletRequest request){
		String productBasicId = request.getParameter("product_basic_id");
		String num = request.getParameter("num");
		if(StringUtils.isBlank(productBasicId) || StringUtils.isBlank(num)){
			return new ApiResult(HttpResultEnum.MIS_PARAM);
		}
		Long beamId = super.getBeamId(request);
		Long userId = super.getUserId(request);
		int i = suppliesService.updateProductBasicSuppliesNum(beamId, userId, productBasicId, num);
		if(i == 1){
			return new ApiResult(HttpResultEnum.SUCCESS.getCode(), "保存成功");
		}else {
			return new ApiResult(HttpResultEnum.EXCEPTION);
		}
	}

	@ResponseBody
	@RequestMapping("/sys/deleteProductBasic")
	public ApiResult deleteProductBasic(HttpServletRequest request){
		String id = request.getParameter("id");
		return suppliesService.deleteProductBasic(id);
	}

}
